// 订单相关API调用 - 与后端OrderApi接口保持一致

import request from '@/utils/request'
import type { Order, OrderSearchParams, OrderPageResponse, OrderItem, Sales } from '@/types/order'

// 分页查询订单列表
export const getOrderList = (params: OrderSearchParams) => {
  // 分离分页参数和搜索参数
  const { pageNo = 1, pageSize = 10, ...searchBean } = params
  
  // 构建请求参数 - pageNo和pageSize作为独立参数，其他作为OrderSerachBean
  const requestParams: any = {
    pageNo,
    pageSize
  }
  
  // 添加搜索条件到请求参数中（后端会将这些绑定到OrderSerachBean）
  if (searchBean.orderNo) requestParams.orderNo = searchBean.orderNo
  if (searchBean.memberId) requestParams.memberId = searchBean.memberId
  if (searchBean.status) requestParams.status = searchBean.status
  
  return request.get<OrderPageResponse>('/api/orders', { params: requestParams })
}

// 更新订单状态
export const updateOrderStatus = (orderId: number, status: string) => {
  return request.put<boolean>(`/api/orders/${orderId}/status`, null, {
    params: { status }
  })
}

// 取消订单
export const cancelOrder = (orderId: number) => {
  return request.put<boolean>(`/api/orders/${orderId}/update`)
}

// 支付订单
export const payOrder = (orderId: number, paymentNo: string) => {
  return request.post<boolean>(`/api/orders/${orderId}/pay`, null, {
    params: { paymentNo }
  })
}

// 创建订单
export const createOrder = (order: Partial<Order>) => {
  return request.post<Order>('/api/orders', order)
}

// 获取订单详情
export const getOrderDetail = (orderId: number) => {
  return request.get<Order>(`/api/orders/id/${orderId}`)
}

// 根据订单号获取订单详情
export const getOrderByNo = (orderNo: string) => {
  return request.get<Order>(`/api/orders/order-no/${orderNo}`)
}

// 查询用户订单（按状态分页）
export const getUserOrders = (userAccount: string, status: string, pageNo: number = 1, pageSize: number = 10) => {
  const params: any = {
    pageNo,
    pageSize
  }
  
  // 添加用户账号作为搜索条件
  if (userAccount) {
    params.memberAccount = userAccount
  }
  
  // 添加状态作为搜索条件（如果有）
  if (status) {
    params.status = status
  }
  
  return request.get<OrderPageResponse>('/api/orders', { params })
}

// 获取订单关键指标
export const getOrderKeyMetrics = (startTime: string, endTime: string) => {
  return request.get<Sales>('/api/orders/key-metrics', {
    params: { startTime, endTime }
  })
}

// 获取支付类型统计
export const getPayTypeStats = (startTime: string, endTime: string) => {
  return request.get<Array<{ name: string, value: number }>>('/api/orders/pay-type', {
    params: { startTime, endTime }
  })
}

// 获取订单项列表
export const getOrderItems = (orderId: number) => {
  return request.get<OrderItem[]>('/api/orderItems', {
    params: { orderId }
  })
}

// 获取订单状态统计（不需要时间参数）
export const getOrderStatusStats = () => {
  return request.get<{ [status: string]: number }>('/api/orders/status-stats')
} 